﻿#include "httphelper.h"


#include <QFile>
#include <QUrl>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QNetworkAccessManager>
#include <QEventLoop>
#include <QTimer>

HttpHelper::HttpHelper(QObject *parent) : QObject(parent)
{

}




/**
 * 单例模式
 * @brief Single::GetInstance
 * @return
 */
HttpHelper& HttpHelper::INSTANCE()
{
    /**
     * 局部静态特性的方式实现单实例。
     * 静态局部变量只在当前函数内有效，其他函数无法访问。
     * 静态局部变量只在第一次被调用的时候初始化，也存储在静态存储区，生命周期从第一次被初始化起至程序结束止。
     */
    static HttpHelper single;
    return single;
}


bool HttpHelper::downloadFileFromURL(const QString &url, const QString &filePath, int timeout){
    QFile f(filePath);
    if (!f.open(QIODevice::WriteOnly)) {
        return false;
    }
    QNetworkAccessManager m;
    QNetworkRequest req;
    req.setUrl(QUrl(url));
    QNetworkReply *reply = m.get(req);
    QEventLoop loop;
    QTimer t;
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    QObject::connect(reply, &QNetworkReply::downloadProgress,
                     [=, &f, &t](){
        f.write(reply->readAll());
        if (t.isActive()) {
            t.start(timeout);
        }
    });
    if (timeout > 0) {
        QObject::connect(&t, &QTimer::timeout, &loop, &QEventLoop::quit);
        t.start(timeout);
    }
    loop.exec();
    if (reply->error() != QNetworkReply::NoError) {
        return false;
    }
    f.close();
    delete reply;
    return true;
}
